from PyQt4.QtGui import *
from PyQt4.QtCore import *


from ui.models import NIModel, SelectionModel, DataItem
from core import cmds, data

class ListViewWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        
        self.list_view = QTreeView(self)
        self.list_view.setModel(NIModel())
        self.list_view.setSelectionModel(SelectionModel(self.list_view.model()))
        self.list_view.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.list_view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.list_view.setAlternatingRowColors(True)
        
        self.list_view.setDragEnabled(True)
        self.list_view.setDragDropMode(QAbstractItemView.DragOnly)
        self.list_view.setDropIndicatorShown(True)
        
        hbox = QHBoxLayout()
        hbox.addWidget(self.list_view)
        self.setLayout(hbox)


class ListView(ni.View):
    data = ni.List()
    group = ni.Function(args=("item",))
    columns = ni.List(itemtype=ni.Function(args=('item',)))
    widget = ListViewWidget
    
    def setup_widget(self, widget):
        widget.connect(widget.list_view, SIGNAL("customContextMenuRequested(const QPoint&)"), 
                       lambda p, widget=widget: self.on_context_menu(p,widget))
    
    def update_widget(self, widget):
        model = widget.list_view.model()
        model.clear()
        items = model.add(self.data)
        for index, col in enumerate(self.columns):
            print 'ADDING COLUMN', col
            model.add_column(items, col, index+1)
        model.group(items, self.group)
        widget.list_view.header().resizeSections(QHeaderView.ResizeToContents)
        
           
    def on_context_menu(self, point, widget):
        print 'CONTEXT'
        obj = widget.list_view.model().itemFromIndex(widget.list_view.currentIndex()).data_obj
        menu = cmds.action_menu(obj, widget)
        if menu is None: return
        menu.popup(QCursor.pos())
